package com.skyinno.mrms.utils;

import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.util.WebUtils;

import com.skyinno.mrms.common.dao.BaseDao;
import com.skyinno.mrms.common.model.JsonModel;


public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Resource(name = "com.sky.common.BaseDao")
    private BaseDao dao;

    @Resource
    private Message message;

    /*
     * (non-Javadoc)
     * 
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        String id = (String) WebUtils.getSessionAttribute(arg0,
                Constants.LOGIN_USER);
        if (StringUtils.isBlank(id)) {
            this.throwException("anew.login", arg0);
        }
        return super.preHandle(arg0, arg1, arg2);
    }

    private void throwException(String key, HttpServletRequest request)
            throws Exception {
        throw new ModelAndViewDefiningException(
                new ModelAndView(
                        Constants.ERROR_VIEW_NAME,
                        Constants.PAGE_DATE_ATTRIBUTE,
                        new JsonModel(
                                "<span style=\"cursor:pointer;text-decoration:underline;\" onclick=\"top.location.href='"
                                        + request.getContextPath()
                                        + "/login/prepareLogin.html'\">"
                                        + message
                                                .getMessage(
                                                        key,
                                                        new String[] { request
                                                                .getContextPath() },
                                                        (Locale) WebUtils
                                                                .getSessionAttribute(
                                                                        request,
                                                                        SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME))
                                        + "</span>")));
    }

}
